package com.tplhk.redis;


import com.tplhk.redis.lock.jedis.util.RedisLockThreadLocalContext;
import com.tplhk.redis.lock.jedis.util.RedisTool;
import com.tplhk.redis.lock.redisson.dto.User;
import com.tplhk.redis.lock.redisson.service.RedissonLockService;
import org.junit.jupiter.api.Test;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static java.lang.Thread.sleep;

@SpringBootTest(classes = RedisApplication.class)
public class RedissonLockDemo {
    @Autowired
    RedissonLockService redissonLockService;

    @Autowired
    private RedissonClient redissonClient;

    @Test
    public void testRedisLock() {
        User user = User.builder().username("xjq").build();
        for (int i = 0; i < 5; i++) {
            startAWork(user, i);
        }
        try {
            TimeUnit.MINUTES.sleep(60);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


    private void startAWork(User user, int i) {
        new Thread(() -> {
            try {
                redissonLockService.test(user, i + "");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }


    @Test
    public void testRedissonClient() throws InterruptedException {
        RLock rLock30 = redissonClient.getLock("xjqLock30");
        // 加锁时间 30 秒
        rLock30.lock(30 * 1000, TimeUnit.MILLISECONDS);

        RLock rLockForever = redissonClient.getLock("rLockForever");
        // 加锁时间 : -1或不传，官方源码使用看门狗的时间做为加锁时间,默认值 30s
        rLockForever.lock();

        RLock rLockTryLockForever = redissonClient.getLock("rLockTryLockForever");
        // 最长等待时间：永久; 加锁时间 : -1或不传，官方源码使用看门狗的时间做为加锁时间,默认值 30s
        rLockTryLockForever.tryLock();

        RLock rLockTryLock88 = redissonClient.getLock("rLockTryLock88");
        // 最长等待时间：10; 加锁时间 : 88s
        rLockTryLock88.tryLock(10, 88, TimeUnit.SECONDS);

        RLock rLockTryLockDogTime = redissonClient.getLock("rLockTryLockDogTime");
        // 最长等待时间：10; 加锁时间 : -1或不传，官方源码使用看门狗的时间做为加锁时间,默认值 30s
        rLockTryLock88.tryLock(10, -1, TimeUnit.SECONDS);

    }

}
